package com.op.teachingliteapp.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.op.teachingliteapp.BuildConfig;
import com.op.teachingliteapp.R;
import com.op.teachingliteapp.bean.CourseBean;
import com.op.teachingliteapp.common.Common;
import com.op.teachingliteapp.common.api.teachinglite.CourseUrl;
import com.op.teachingliteapp.database.dao.CourseDao;
import com.op.teachingliteapp.fragment.SettingsFragment;
import com.op.teachingliteapp.fragment.UserInformationFragment;
import com.op.teachingliteapp.fragment.course.CourseFragment;
import com.op.teachingliteapp.fragment.smartpan.SmartPanFragment;
import com.op.teachingliteapp.util.DirUtils;
import com.op.teachingliteapp.util.SharedPreferenceUtil;
import com.op.teachingliteapp.util.StringUtils;
import com.op.teachingliteapp.util.asynctask.HttpPostTask;
import com.op.teachingliteapp.util.asynctask.OnTaskProcessListener;
import com.op.teachingliteapp.util.network.NetworkUtils;
import com.op.teachingliteapp.widget.RoundImageView;

public class HomeActivity extends Activity {

	private static final String TAG = HomeActivity.class.getSimpleName();
	private String getCourseUserId;
	private RelativeLayout userLoad;

	private boolean isExit = false;
	private TextView mainTitle, userName;
	private Button YunKeTangBtn; // cloudClassBtn
	private Button cloudDiskBtn; // 云盘
	private Button settingsBtn; // settingsBtn
	private ImageButton reFlash;// 刷新按钮
	private RoundImageView imageButton;// 头像按钮
	private Resources resources;
	private LinearLayout informationBar;// 界面顶端的Bar
	private DisplayImageOptions options;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 2. 设置option, 一般默认

		options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.ic_stub).showImageForEmptyUri(R.drawable.ic_empty).showImageOnFail(R.drawable.ic_error).cacheInMemory(true).cacheOnDisk(true).considerExifParams(true).bitmapConfig(Bitmap.Config.RGB_565).build();
		// 修改控件布局背景
		resources = HomeActivity.this.getResources();
		// 判断是否是第一次进入HomeActivity
		SharedPreferences preferences = getSharedPreferences("TeachingLite", Context.MODE_PRIVATE);
		Boolean needUpdataData = preferences.getBoolean(Common.Prefs.NEED_UPDATA_DATA, true);

		if (BuildConfig.DEBUG) {
			Log.i(TAG, "oncreate");
		}
		setContentView(R.layout.activity_home);
		// 刷新按钮
		reFlash = (ImageButton) findViewById(R.id.reflash);
		mainTitle = (TextView) findViewById(R.id.top_view_one);

		informationBar = (LinearLayout) findViewById(R.id.activity_home_bar);

		if (getFragmentManager().findFragmentById(R.id.main_show) == null) {
			switchFragment(new CourseFragment());

		}

		// 前一个参数是去userId的key，我之前设置的是userId本身，所以这样取,第二个参数为缺省值，如果preference中不存在该key，将返回缺省值
		getCourseUserId = preferences.getString(Common.Prefs.USER_ID, "");
		// 判断Wifi和GSM网络状况，被邱老师改过
		if (NetworkUtils.isNetworkAvailable(this)) {
			getCoursePost();
			if (needUpdataData) {
				// 如果是第一次进入HomeActivity，从网络 获取课程列表
				getCoursePost();
			}
		} else {
			// 如果没有Wifi无连接 则从数据库中取课程列表
			CourseDao courseDao = new CourseDao(HomeActivity.this, getCourseUserId);
			List<CourseBean> courses = courseDao.getCoursesByUserId(getCourseUserId);

			String str = courses.size() + "\\";
			for (int i = 0; i < courses.size(); i++) {
				str += courses.get(i).getName() + "\\";
			}
			switchFragment(new CourseFragment());
			Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
		}
		// 个人信息
		userLoad = (RelativeLayout) findViewById(R.id.userr_load_nformation);
		imageButton = (RoundImageView) findViewById(R.id.load);
		userName = (TextView) findViewById(R.id.userName);
		// 个人信息头像设置
		ImageLoader.getInstance().displayImage(preferences.getString("imageUrl", ""), imageButton, options);

		userName.setText(preferences.getString("userName", ""));
		imageButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				reFlash.setVisibility(View.GONE);
				informationBar.setVisibility(View.VISIBLE);
				Drawable btnDrawable = resources.getDrawable(R.drawable.menu_login_bg_pressed);
				userLoad.setBackgroundDrawable(btnDrawable);
				mainTitle.setText("个人信息");
				YunKeTangBtn.setBackgroundResource(R.drawable.buttom_home3);
				cloudDiskBtn.setBackgroundResource(R.drawable.buttom_cloud3);
				settingsBtn.setBackgroundResource(R.drawable.buttom_set3);
				switchFragment(new UserInformationFragment());
			}
		});

		// 云课堂
		YunKeTangBtn = (Button) findViewById(R.id.buttom_home);
		YunKeTangBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				informationBar.setVisibility(View.VISIBLE);
				mainTitle.setText("课程选择");
				reFlash.setVisibility(View.VISIBLE);
				Drawable btnDrawable = resources.getDrawable(R.drawable.home_activity_user_information_background);
				userLoad.setBackgroundDrawable(btnDrawable);
				YunKeTangBtn.setBackgroundResource(R.drawable.buttom_home1);
				cloudDiskBtn.setBackgroundResource(R.drawable.buttom_cloud3);
				settingsBtn.setBackgroundResource(R.drawable.buttom_set3);
				switchFragment(new CourseFragment());
			}
		});

		// 云盘
		cloudDiskBtn = (Button) findViewById(R.id.buttom_cloud);
		cloudDiskBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				reFlash.setVisibility(View.VISIBLE);
				informationBar.setVisibility(View.GONE);
				Drawable btnDrawable = resources.getDrawable(R.drawable.home_activity_user_information_background);
				userLoad.setBackgroundDrawable(btnDrawable);
				cloudDiskBtn.setBackgroundResource(R.drawable.buttom_cloud1);
				YunKeTangBtn.setBackgroundResource(R.drawable.buttom_home3);
				settingsBtn.setBackgroundResource(R.drawable.buttom_set3);

				Toast.makeText(getApplicationContext(), "冲哥正在熬夜开发", Toast.LENGTH_SHORT).show();
				switchFragment(new SmartPanFragment());
			}
		});

		// 设置
		settingsBtn = (Button) findViewById(R.id.buttom_set);
		settingsBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mainTitle.setVisibility(View.VISIBLE);
				mainTitle.setText("设置");
				reFlash.setVisibility(View.GONE);
				Drawable btnDrawable = resources.getDrawable(R.drawable.home_activity_user_information_background);
				userLoad.setBackgroundDrawable(btnDrawable);
				settingsBtn.setBackgroundResource(R.drawable.buttom_set1);
				YunKeTangBtn.setBackgroundResource(R.drawable.buttom_home3);
				cloudDiskBtn.setBackgroundResource(R.drawable.buttom_cloud3);
				switchFragment(new SettingsFragment());
			}
		});
	}

	/*
	 * 监听刷新按钮
	 */
	public void reFlashOnClick(View v) {
		reFlash.setClickable(false);
		getCoursePost();
	}

//	/*
//	 * 监听更多按钮
//	 */
//	public void morePopupOnClick(View v) {
//		PopupMenu popupMenu = new PopupMenu(HomeActivity.this, v);
//		popupMenu.getMenuInflater().inflate(R.menu.popup_menu_main, popupMenu.getMenu());
//		popupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
//
//			@Override
//			public boolean onMenuItemClick(MenuItem item) {
//				switch (item.getItemId()) {
//				case R.id.First:
//					Toast.makeText(getBaseContext(), "功能一", Toast.LENGTH_SHORT).show();
//					break;
//				case R.id.Second:
//					Toast.makeText(getBaseContext(), "功能二", Toast.LENGTH_SHORT).show();
//					break;
//				case R.id.Third:
//					Toast.makeText(getBaseContext(), "功能三", Toast.LENGTH_SHORT).show();
//					break;
//				default:
//					break;
//				}
//				return false;
//			}
//		});
//
//		popupMenu.show();
//	}

	private void ToQuitTheApp() {
		if (isExit) {
			// ACTION_MAIN with category CATEGORY_HOME 启动主屏幕
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_HOME);
			startActivity(intent);
			android.os.Process.killProcess(android.os.Process.myPid());
			System.exit(0);// 使虚拟机停止运行并退出程序
			// finish();
		} else {
			isExit = true;
			Toast.makeText(HomeActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
			mHandler.sendEmptyMessageDelayed(0, 3000);// 3秒后发送消息
		}
	}

	// 创建Handler对象，用来处理消息
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {// 处理消息
			super.handleMessage(msg);
			isExit = false;
		}
	};

	@Override
	protected void onStart() {
		System.out.println("stop");
		super.onStart();
	}

	@Override
	protected void onDestroy() {
		System.out.println("out");
		super.onDestroy();
	}

	/*
	 * 用post发送ID获得课程数据
	 * 
	 * @author 陈宇瀚
	 */

	public void getCoursePost() {
		// 做异步请求
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Common.Prefs.USER_ID, getCourseUserId));
		HttpPostTask task = new HttpPostTask(HomeActivity.this, CourseUrl.GET_COURSE_BY_USER_ID, params);
		task.setTaskListener(new OnTaskProcessListener() {
			@Override
			public void prepare() {
				// 清空所有课程
				CourseDao courseDao = new CourseDao(HomeActivity.this, getCourseUserId);
				courseDao.empty();
			}

			@Override
			public void completed(String result) {

				// 存储数据
				try {
					if (!StringUtils.isEmptyOrStringNull(result)) {
						JSONObject jsonObject = new JSONObject(result);
						Log.i("------------------------------", "dsa______________________________________________:" + result);

						JSONArray jsonArray = jsonObject.getJSONObject("resultMap").getJSONArray("courseList");

						for (int i = 0; i < jsonArray.length(); i++) {
							JSONObject courseObject = jsonArray.getJSONObject(i);
							CourseBean courseBean = new CourseBean();
							courseBean.fillAttributeByJson(courseObject);
							CourseDao courseDao = new CourseDao(HomeActivity.this, getCourseUserId);
							courseDao.insert(courseBean);
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

				getFragmentManager().findFragmentById(R.id.main_show).onResume();
				reFlash.setClickable(true);
				// 建立相应课程的文件夹
				CourseDao courseDao = new CourseDao(HomeActivity.this, getCourseUserId);
				List<CourseBean> courses = courseDao.getCoursesByUserId(getCourseUserId);
				createFolders(getCourseUserId, courses);

			}

		});
		task.execute();
		// 将判断是否第一次登陆的数据放入SharedPreference
		HashMap<String, Object> needUpdataData = new HashMap<String, Object>();
		needUpdataData.put("needUpdataData", false);
		SharedPreferenceUtil.saveData(HomeActivity.this, needUpdataData);

	}

	private void switchFragment(Fragment fragment) {
		getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
		getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.main_show, fragment).commit();

	}

	@Override
	public void onBackPressed() {
		if (getFragmentManager().getBackStackEntryCount() == 1) {
			ToQuitTheApp();
			return;
		}
		super.onBackPressed();
	}

	/**
	 * 创建 相应课程的文件夹
	 * 
	 * @param userId
	 * @param list
	 */
	public void createFolders(final String userId, final List<CourseBean> list) {

		new Thread(new Runnable() {

			@Override
			public void run() {
				DirUtils dirUtils = new DirUtils(HomeActivity.this, userId);
				List<String> courses = new ArrayList<String>();
				for (int i = 0; i < list.size(); i++) {
//					Log.i(TAG, list.get(i).getName());
					courses.add(list.get(i).getName());
				}
				dirUtils.initDirs(courses);
//				dirUtils.getFilesNameByDir("Course");
			}
		}).start();
	}
}
